const { result ,teamDocJSON} =require('../config/result')
const {transformExcel,checkFileExistsSync} =require('../utils/index')
const { saveteamdoc,saveteamdocInput,getDocByname,getallDocs,getDocInputBydocTplid,
        getDocsHistoryBydocTplid,delteamdocbytplid,delteamdocHis,updateDocSharesOrState} =require('../db/teamdoc')
const LuckyExcel =require('luckyexcel')
class teamdocConntroller{
  async updateShareOrState(ctx){
    const {id,shares,sharenames='',state,flag} = ctx.request.body
    await updateDocSharesOrState(id,shares,sharenames,state,flag)
    result.success=true;
    result.message='更新成功'
    result.token=''
    result.total=0
    result.data=null
    ctx.body=result
  }
  async getAllDocs(ctx){
    try{
      let id=ctx.state.user.id
      const ret=await getallDocs(id)
      result.success=true;
      result.message='获取成功'
      result.token=''
      result.total=0
      result.data=ret
      ctx.body=result;  
    }catch(e){
      result.success=false;
      result.message='获取失败'
      result.token=''
      result.total=0
      result.data=null
      ctx.body=result; 
    }
  }
  async getteamDocByName(ctx){
    try{
      const {docname} = ctx.request.body
      const ret=await getDocByname(docname)
      result.success=true;
      result.message='获取成功'
      result.token=''
      result.total=0
      result.data=ret
      ctx.body=result;  
    }catch(e){
      result.success=false;
      result.message='获取失败'
      result.token=''
      result.total=0
      result.data=null
      ctx.body=result; 
    }
  }
  
  async uploadInputteamdoc(ctx){
   //console.log('uploadInputteamdoc')
      const file = ctx.request.files?.file;    
      if(file)
        {
          //将上传文件信息存入数据库
          try{
            const data = ctx.request.body 
            const {id,docname} = data 
            const url=`${ctx.origin}/upload/teamdoc/${file.originalFilename}` 
            const savepath=file.filepath                                
            const ret =  await saveteamdocInput(data,savepath,url,docname)                                  
            let newID=0
            if(id <1){
              newID = ret[0] //新增后的返回ID值
            }
            else{
              newID = id
            }  
          //要将文件存储信息存到数据库
          result.success=true;
          result.message='保存成功'
          result.token=''
          result.total=0
          result.data={
            id:newID,
            url:url,
            oldFileName:file.originalFilename,
            newFileName:docname,
            savepath:savepath
          }
          }catch(e){
            ctx.app.emit('error',e.message,ctx)  
          }      
        }   
        else{
          result.success=false;
          result.message='上传失败'
          result.token=''
          result.total=0
          result.data=null
        }
        //console.log(result)
        ctx.body=result;  
  }
  async uploadteamdoc(ctx){
    const file = ctx.request.files?.file;    
    if(file)
      {
        //将上传文件信息存入数据库
        try{
          const data = ctx.request.body 
          const {id} = data 
          const url=`${ctx.origin}/upload/teamdoc/tpl/${file.originalFilename}` 
          let displayname = file.originalFilename.split('_')[2]
          const savepath=file.filepath                                
          const ret =  await saveteamdoc(data,savepath,url,displayname,file.originalFilename)                                  
          let newID=0
          if(id <1){
            newID = ret[0] //新增后的返回ID值
          }
          else{
            newID = id
          }  
        //要将文件存储信息存到数据库
        result.success=true;
        result.message='上传成功'
        result.token=''
        result.total=0
        result.data={
          id:newID,
          url:url,
          oldFileName:file.originalFilename,
          newFileName:displayname,
          savepath:savepath
        }
        }catch(e){
          ctx.app.emit('error',e.message,ctx)  
        }      
      }   
      else{
        result.success=false;
        result.message='上传失败'
        result.token=''
        result.total=0
        result.data=null
      }
      //console.log(result)
      ctx.body=result;  
  }

  async getteamdocTplbyPath(ctx)
  {
    //console.log('getteamdocTplbyPath')
    const {filename} = ctx.request.body
    let resultData =''
    if(!checkFileExistsSync(filename))
    {
      console.log(`文件不存在：${filename}`)
      ctx.body=JSON.stringify(teamDocJSON)
    }
    else{
      await transformExcel(filename)
      .then((exportJson)=>{
        result.success=true;
        result.message='获取成功'
        result.token=''
        result.total=0
        result.data=exportJson.sheets
        //resultData=exportJson.sheets
        ctx.body= result
      })
      .catch((err)=>{
        result.success=true;
        result.message='获取成功'
        result.token=''
        result.total=0
        result.data=exportJson.sheets
        //resultData=exportJson.sheets
        ctx.body= result
        //console.log(err)
        //resultData= JSON.stringify(teamDocJSON)
        //ctx.response.body=resultData
      })
    }

  }
  async getteamDocByID(ctx){
    const {gridKey} = ctx.request.body
    //console.log(ctx.request.body)
    //gridKey 为 teamdoc id,要找出所有录入的文档
    //console.log(`getteamDocByID:${gridKey}`)
    const tparams=gridKey.split('*')
    const savepath=tparams[0]
    const flag=tparams[1]
    //console.log('flag:',flag)
    let fileaname=''
    if(flag.trim() === '1'){
      fileaname = savepath
      //console.log(`filenameD:`,fileaname)
    }else{
      const ret=await getDocInputBydocTplid(savepath,0)     
      if(ret && ret.length>0)
      {
          fileaname =ret[0].savepath
      }     
    }

    let resultData =''
    if(!checkFileExistsSync(fileaname))
    {
      console.log(`文件不存在：${fileaname}`)
      ctx.body=JSON.stringify(teamDocJSON)
    }
    else{
      await transformExcel(fileaname)
      .then((exportJson)=>{
        resultData=exportJson.sheets
        ctx.response.body= JSON.stringify(resultData)
      })
      .catch((err)=>{
        console.log(err)
        resultData= JSON.stringify(teamDocJSON)
        ctx.response.body=resultData
      })
    }
  } 

  async getteamDocHistoryByteamdocID(ctx){
    const {teamdocid} = ctx.request.body
    const ret=await getDocsHistoryBydocTplid(teamdocid)
    result.success=true;
    result.message='获取成功'
    result.token=''
    result.total=0
    result.data=ret
    //console.log("log",ret)
    ctx.body=result
  }

  async delteamdocbytplid(ctx){
    const {teamdocid} = ctx.request.body
    await delteamdocbytplid(teamdocid)
    result.success=true;
    result.message='删除成功'
    result.token=''
    result.total=0
    result.data=null
    ctx.body=result
  }
  async delteamdocHis(ctx){
    const {teamdocid} = ctx.request.body
    await delteamdocHis(teamdocid)
    result.success=true;
    result.message='删除成功'
    result.token=''
    result.total=0
    result.data=null
    ctx.body=result
  }
}


module.exports= new teamdocConntroller()